package top.kikt.book.core.handlers

import okhttp3.HttpUrl.Companion.toHttpUrl
import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.util.bookText
import top.kikt.book.util.metaContentWithProperty
import top.kikt.book.util.resolve

class BiQuZW : BaseBookHandler() {
    override val host: String
        get() = "www.biquzw.la"

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val name = document.metaContentWithProperty("og:novel:book_name")
        val author = document.metaContentWithProperty("og:novel:author")
        val coverImageUrl = document.metaContentWithProperty("og:image")

        return BookMetaEntity(name, url, url, author, coverImageUrl)
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val result = ArrayList<ChapterMetaEntity>()

        val nodes = document.select("#list > dl > dd > a")

        for ((index, node) in nodes.withIndex()) {
            val name = node.text().trim()
            val link = menuUrl.resolve(node.attr("href"))
            result.add(
                ChapterMetaEntity(name, index, link, node)
            )
        }

        return result
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val url = chapterMetaEntity.url
        val doc = url.toHttpUrl().toDocument() ?: return null
        val text = doc.select("#content").bookText()
        return ChapterEntity(chapterMetaEntity.name, chapterMetaEntity.index, text)
    }
}